using UnityEngine;
using UnityEngine.UI;

namespace RGuang.PlathformCtrl
{

    public class ClearTimer : MonoBehaviour
    {
        [SerializeField] VoidEventChannel levelStartedEventChannel;
        [SerializeField] VoidEventChannel levelClearedEventChannel;
        [SerializeField] VoidEventChannel playerDefeatedEventChannel;
        [SerializeField] StringEventChannel clearTimeTextEventChannel;

        [SerializeField] Text txtTime;
        bool stop = true;
        float clearTime;
        private void OnEnable()
        {
            levelStartedEventChannel.AddListener(LevelStart);
            levelClearedEventChannel.AddListener(LevelClear);
            playerDefeatedEventChannel.AddListener(HideUI);
        }
        private void OnDisable()
        {
            playerDefeatedEventChannel.RemoveListener(HideUI);
            levelStartedEventChannel.RemoveListener(LevelStart);
            levelClearedEventChannel.RemoveListener(LevelClear);
        }

        void FixedUpdate()
        {
            if (stop) return;
            clearTime += Time.fixedDeltaTime;
            txtTime.text = System.TimeSpan.FromSeconds(clearTime).ToString(@"mm\:ss\:ff");
        }

        void LevelStart()
        {
            stop = false;
        }
        void LevelClear()
        {
            HideUI();
            clearTimeTextEventChannel.Broadcast(txtTime.text);
        }
        void HideUI()
        {
            stop = true;
            GetComponent<Canvas>().enabled = false;
        }
    }
}

